package com.niannian.activity;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.niannian.util.AsyncHandle;
import com.niannian.util.Common;
import com.niannian.util.ErrorCode;
import com.niannian.util.MessageRecieveManager;
import com.niannian.util.MyDate;
import com.niannian.util.UmengPage;
import com.niannian.adapter.RegardsReceiveAdaper;
import com.niannian.bean.GreetingNewsBean;
import com.niannian.util.LoadDataUtil;
import com.niannian.view.PullToRefreshListView;
import com.niannian.view.PullToRefreshListView.IXListViewListener;
import com.niannian.web.nnSyncApi;
import com.niannian.BaseActivity;
import com.niannian.R;
import com.umeng.analytics.MobclickAgent;

/**
 * 收到的问候
 * 
 * @author shengl
 * 
 */
public class RegardsActivity extends BaseActivity {
	public static final int PLAY_VOICE = 1;
	public static final int LIST_FOOTER_HIDE = 3;// 隐藏底部
	public static final int DELETE_SEND_REGARDS = 4;//

	// 动态显示列表
	private PullToRefreshListView list_greeting_news_info;
	private RegardsReceiveAdaper gAdapter;

	TextView tv_greeting_news_no_data;// 没有数据提示

	Boolean isFirst = false;
	private LoadData loadData;// 加载动态
	String playPath = "";// 需要播放的路径
	String playingPath = "";// 当前播放路径
	int senderid = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_regards_news);
		senderid = getIntent().getIntExtra("id", 0);

		initView();
		setLister();
		initTopView();
		loadData = new LoadData();
		loadData.setContext(this);
		loadData.loadOnlyDb(false, getParameters());
		loadData.refresh(getParameters());

		try {
			Intent msgIntent = new Intent(MessageRecieveManager.UPDATA_NEWSS_TOTAL_COUNT_ACTION);
			String msg_type = "R";
			msgIntent.putExtra("msg_type", msg_type);
			msgIntent.putExtra("sender", senderid);
			sendBroadcast(msgIntent);

			NotificationManager notiManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			notiManager.cancel(senderid);
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	// 头部视图
	private ImageView iv_top_left, iv_top_right;
	private TextView top_title;
	private LinearLayout iv_top_left2, top_title2;

	private void initTopView() {
		iv_top_left = (ImageView) findViewById(R.id.iv_top_left);
		iv_top_left2 = (LinearLayout) findViewById(R.id.iv_top_left2);
		iv_top_left.setVisibility(View.VISIBLE);
		iv_top_left2.setVisibility(View.GONE);

		top_title = (TextView) findViewById(R.id.top_title);
		top_title2 = (LinearLayout) findViewById(R.id.top_title2);
		top_title.setVisibility(View.VISIBLE);
		top_title2.setVisibility(View.GONE);
		top_title.setText("问候");

		iv_top_right = (ImageView) findViewById(R.id.iv_top_right);
		iv_top_right.setVisibility(View.GONE);

		iv_top_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				myfinish();
			}
		});
	}

	private void initView() {
		list_greeting_news_info = (PullToRefreshListView) findViewById(R.id.list_greeting_news_info);
		list_greeting_news_info.setXListViewListener(xListViewListener);
		list_greeting_news_info.setPullLoadEnable(false);
		// list_greeting_news_info.forceShowHeaderRefresh();
		gAdapter = new RegardsReceiveAdaper(this, nHandler);
		list_greeting_news_info.setAdapter(gAdapter);
		gAdapter.setAdapter(gAdapter);

		tv_greeting_news_no_data = (TextView) findViewById(R.id.tv_greeting_news_no_data);
		tv_greeting_news_no_data.setVisibility(View.GONE);
	}

	private void updateContent(List<GreetingNewsBean> beans) {
		if (gAdapter == null) {
			gAdapter = new RegardsReceiveAdaper(this, nHandler);
			list_greeting_news_info.setAdapter(gAdapter);
		}
		gAdapter.getFDatasList().addAll(beans);
		gAdapter.notifyDataSetChanged();
		if (gAdapter.getCount() > 0) {
			tv_greeting_news_no_data.setVisibility(View.GONE);
		} else {
			tv_greeting_news_no_data.setVisibility(View.VISIBLE);
		}
	}

	private void setLister() {

	}

	private Map<String, Object> getParameters() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("lasttime", 0);
		return map;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (RESULT_OK != resultCode) {
			return;
		}
		switch (requestCode) {
		case PushRegardsActivity.FROM_EDIT_REGARDS:

			int rid = data.getIntExtra("rid", 0);
			int sent_time = data.getIntExtra("sent_time", 0);

			for (int i = 0; i < gAdapter.getFDatasList().size(); i++) {
				if (!Common.empty(gAdapter.getFDatasList().get(i).getGreetingNewsBean2())
						&& gAdapter.getFDatasList().get(i).getGreetingNewsBean2().getId() == rid) {
					gAdapter.getFDatasList().get(i).getGreetingNewsBean2().setSent_time(sent_time);
					gAdapter.notifyDataSetChanged();
					break;
				}
			}
			break;

		case PushRegardsActivity.FROM_PUSH_REGARDS_CONFIRM_REPY:
			int id = data.getIntExtra("id", 0);
			for (int i = 0; i < gAdapter.getFDatasList().size(); i++) {
				if (gAdapter.getFDatasList().get(i).getId() == id) {
					List<GreetingNewsBean> listReply = databaseapi.loadreply(userInfoManager.id, "R", id);
					if (!Common.empty(listReply)) {
						gAdapter.getFDatasList().get(i).setGreetingNewsBean2(listReply.get(0));
					}
					gAdapter.notifyDataSetChanged();
					break;
				}
			}
			break;

		default:
			break;
		}
	}

	Handler nHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case PLAY_VOICE:

				break;
			case LIST_FOOTER_HIDE:
				list_greeting_news_info.FooterHide();
				break;
			case DELETE_SEND_REGARDS:
				Map<String, Object> paramMap = new HashMap<String, Object>();
				paramMap.put("rid", msg.arg1);
				// familyAdapter.getFDatasList().remove(msg.arg2);
				// familyAdapter.notifyDataSetChanged();
				new DeleteSend().init(RegardsActivity.this, paramMap, true, "撤销问候...").execute();

				break;
			default:
				break;
			}
		};
	};

	class LoadData extends LoadDataUtil {

		@Override
		protected String runServerTask(Map<String, Object> parameters) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			return nnSyncApi.getRegardList(lasttime, senderid);
		}

		protected void serverTaskFinally(Map<String, Object> params) {
			onLoad();
		}

		@Override
		protected boolean handleServerSuccess(JSONObject json, Map<String, Object> parameters) {
			onLoad();
			try {
				if (json.getInt("code") == ErrorCode.OK) {
					int lasttime = 0;
					if (!Common.empty(parameters.get("lasttime"))) {
						lasttime = (Integer) parameters.get("lasttime");
					}
					databaseapi.updateGreetingReceive(userInfoManager.id, json.getJSONArray("data"), lasttime, "R", senderid);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();

			}
			return false;
		}

		@Override
		protected boolean loadMoreDB(Map<String, Object> parameters, boolean refresh) {
			int lasttime = 0;
			if (!Common.empty(parameters.get("lasttime"))) {
				lasttime = (Integer) parameters.get("lasttime");
			}
			List<GreetingNewsBean> fdata = databaseapi.loadGreetingReceive(userInfoManager.id, lasttime, "R", senderid);
			list_greeting_news_info.listNotData(true);
			if (fdata != null) {
				// if (fdata == null || fdata.size() == 0) {
				//
				// list_greeting_news_info.listNotData(false);
				// nHandler.sendEmptyMessageDelayed(LIST_FOOTER_HIDE, 3000);
				// }
				// if (fdata.size() != 10) {
				// list_greeting_news_info.listNotData(false);
				// nHandler.sendEmptyMessageDelayed(LIST_FOOTER_HIDE, 3000);
				// } else {
				// list_greeting_news_info.listNotData(true);
				// }
				if (refresh) {
					gAdapter.getFDatasList().clear();
				}
				updateContent(fdata);
			} else {
				if (refresh) {
					if (gAdapter.getCount() > 0) {
						tv_greeting_news_no_data.setVisibility(View.GONE);
					} else {
						tv_greeting_news_no_data.setVisibility(View.VISIBLE);
					}
				}
			}

			return false;
		}
	}

	private IXListViewListener xListViewListener = new IXListViewListener() {
		@Override
		public void onRefresh() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					loadData.refresh(getParameters());

				}
			}, 500);
		}

		@Override
		public void onLoadMore() {
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					Map<String, Object> map = new HashMap<String, Object>();
					GreetingNewsBean last = null;
					try {
						last = (GreetingNewsBean) gAdapter.getItem((gAdapter.getCount() - 1));
					} catch (Exception e) {
						last = null;
					}
					if (last != null) {
						map.put("lasttime", last.getSent_time());
					} else {
						map.put("lasttime", 0);
					}
					loadData.load(map);
				}
			}, 150);
		}
	};

	protected class DeleteSend extends AsyncHandle {

		protected void errorFinally(Map<String, Object> paramMap) {
			Common.tip(RegardsActivity.this, "撤销问候失败");
		}

		protected void handleData(JSONObject paramJSONObject, Map<String, Object> paramMap) throws JSONException {
			int retCode = paramJSONObject.getInt("code");
			if (retCode == ErrorCode.OK) {
				int id = (Integer) paramMap.get("rid");
				databaseapi.deleteSendReceive(userInfoManager.id, id);

				for (int i = 0; i < gAdapter.getCount(); i++) {
					if (!Common.empty(gAdapter.getFDatasList().get(i).getGreetingNewsBean2())
							&& gAdapter.getFDatasList().get(i).getGreetingNewsBean2().getId() == id) {
						gAdapter.getFDatasList().get(i).getGreetingNewsBean2().setIsdelete(1);
						gAdapter.notifyDataSetChanged();
						break;
					}
				}

				Common.tip(RegardsActivity.this, "撤销问候成功");
			} else {
				Common.tip(RegardsActivity.this, paramJSONObject.getString("msg"));
			}
		}

		protected String runTask(Map<String, Object> paramMap) {
			String pid = paramMap.get("rid").toString();
			return nnSyncApi.deleteSendR(pid);
		}
	}

	private void onLoad() {// 显示拉出来时候的一些信息
		list_greeting_news_info.stopRefresh();
		list_greeting_news_info.stopLoadMore();
		list_greeting_news_info.setRefreshTime(MyDate.getDate());
	}

	@Override
	public void onBackPressed() {

		myfinish();
	}

	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart(UmengPage.REGARD_FACE);
		MobclickAgent.onResume(this);
	}

	@Override
	public void onPause() {
		super.onPause();
		MobclickAgent.onPageEnd(UmengPage.REGARD_FACE);
		MobclickAgent.onPause(this);
	}
}
